package com.buddies.lottery.ui.wallet.bank;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.buddies.lottery.App;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.data.bean.Bank;
import com.buddies.lottery.data.bean.BankResponse;
import com.buddies.lottery.data.resp.CheckWalletPwdResponse;
import com.buddies.lottery.ui.MainActivity;
import com.r0adkll.slidr.Slidr;

public class BankActivity extends BaseActivity<BankContract.Presenter> implements View.OnClickListener, BankContract.View {

    private Spinner mSpinnerCardName;
    private Button btnSubmit;
    private EditText etCardUser;
    private EditText etCardNo;
    private EditText etPwd;
    private ImageView ivClearCardUser;
    private ImageView ivClearNo;
    private ImageView ivClearPwd;

    private Bank mBank;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawableResource(R.color.transparent);
        Slidr.attach(this, App.getSlidrConfig());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bank;
    }

    @Override
    protected void initView() {
        mSpinnerCardName = findViewById(R.id.spinner_name);

        btnSubmit = (Button) findViewById(R.id.btn_submit);
        etCardUser = (EditText) findViewById(R.id.et_name);
        etCardNo = (EditText) findViewById(R.id.et_no);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        ivClearCardUser = (ImageView) findViewById(R.id.iv_clear);
        ivClearNo = (ImageView) findViewById(R.id.iv_clear_no);
        ivClearPwd = (ImageView) findViewById(R.id.iv_clear_pwd);

        btnSubmit.setOnClickListener(this);
        ivClearCardUser.setOnClickListener(this);
        ivClearPwd.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        setUp();
        setTitle(getResources().getString(R.string.bank_manage));

        mPresenter = new BankPresenter(this);

        etCardUser.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClearCardUser.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        etCardUser.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                ivClearCardUser.setVisibility(etCardUser.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        etCardNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClearNo.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        etCardNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                ivClearNo.setVisibility(etCardUser.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                ivClearPwd.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        etPwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                ivClearPwd.setVisibility(etPwd.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        setCommitBtnEnable();

        checkWalletPwd();
    }

    private void checkWalletPwd() {
        View container = LayoutInflater.from(getActivity()).inflate(R.layout.item_check_wallet_pwd, null);

        final EditText editText = (EditText) container.findViewById(R.id.et_pwd);
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();

        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("银行卡管理")
                .setView(container)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String pwd = editText.getText().toString();
                        if (TextUtils.isEmpty(pwd)) {
                            ToastUtils.showShort(R.string.wallet_pwd_require);

                            checkWalletPwd();
                            return;
                        }

                        mPresenter.checkWalletPwd(EncryptUtils.encryptMD5ToString(pwd));
                        showProgressDialog("正在验证", false);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setCancelable(false)
                .create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                editText.post(new Runnable() {
                    @Override
                    public void run() {
                        KeyboardUtils.showSoftInput(editText);
                    }
                });
            }
        });
        dialog.show();
    }

    @Override
    public void onCheckWalletPwdSuccess(CheckWalletPwdResponse response) {
        hideProgressDialog();
        if (response.result) {
            mPresenter.loadBank();
            showProgressDialog("正在加载");
        } else {
            ToastUtils.showShort("您输入的资金密码有误！");
            checkWalletPwd();
        }
    }

    public void setCommitBtnEnable() {
        boolean enabled = etCardUser.length() > 0 && etCardNo.length() > 0 && etPwd.length() > 0;
        btnSubmit.setEnabled(enabled);
        if (!enabled) {
            btnSubmit.setAlpha(0.3f); //TextColor(getResources().getColor(R.color.black_30_percent_transparent));
        } else {
            btnSubmit.setAlpha(1.0f); //TextColor(getResources().getColor(R.color.black));
        }
    }

    @Override
    public void onBankLoaded(BankResponse response) {
        hideProgressDialog();

        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, response.bank_list);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinnerCardName.setAdapter(spinnerAdapter);

        mBank = response.bank;
        if (mBank != null) {
            int position = response.bank_list.contains(mBank.card_name) ? response.bank_list.indexOf(mBank.card_name) : 0;
            mSpinnerCardName.setSelection(position);

            etCardUser.setText(mBank.card_user);
            etCardNo.setText(mBank.card_no);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                if (checkCardName() && checkCardUser() && checkCardNo() && checkPwd()) {
                    requestUpdateBank();
                }
                KeyboardUtils.hideSoftInput(getActivity());
                break;

            case R.id.iv_clear:
                etCardUser.setText("");
                break;

            case R.id.iv_clear_pwd:
                etPwd.setText("");
                break;

            default:
                break;
        }
    }

    private void requestUpdateBank() {
        String cardName = getCardName();
        String cardNo = getCardNo();
        String cardUser = getCardUser();
        String walletPwd = getPwd();

        mPresenter.postUpdateBank(cardName, cardNo, cardUser, EncryptUtils.encryptMD5ToString(walletPwd));
        showProgressDialog(R.string.register_commit_processing);
    }

    @Override
    public void onUpdateBankSuccess() {
        hideProgressDialog();
        ToastUtils.showLong(R.string.bank_update_success);

        if (isTaskRoot()) {
            MainActivity.launch(getActivity());
        }

        mBank.card_name = getCardName();
        mBank.card_user = getCardUser();
        mBank.card_no = getCardNo();
    }

    private boolean checkCardName() {
        String cardName = getCardName();

        boolean check = false;
        if (TextUtils.isEmpty(cardName)) {
            showToast(getResources().getString(R.string.bank_card_name_require));
        } else {
            check = true;
        }

        return check;
    }

    private boolean checkCardUser() {
        String cardUser = getCardUser();

        boolean check = false;
        if (TextUtils.isEmpty(cardUser)) {
            showToast(getResources().getString(R.string.bank_card_user_require));
        } else {
            check = true;
        }

        return check;
    }

    private boolean checkCardNo() {
        String cardNo = getCardNo();

        boolean check = false;
        if (TextUtils.isEmpty(cardNo)) {
            showToast(getResources().getString(R.string.bank_card_no_require));
        } else {
            check = true;
        }

        return check;
    }

    public String getCardName() {
        return mSpinnerCardName.getSelectedItem().toString();
    }

    public String getCardUser() {
        return etCardUser.getText().toString();
    }

    public String getCardNo() {
        return etCardNo.getText().toString();
    }

    private boolean checkPwd() {
        String pwd = getPwd();

        boolean check = false;
        if (TextUtils.isEmpty(pwd)) {
            showToast(getResources().getString(R.string.login_password_require));
        } else if (pwd.length() < 6 || pwd.length() > 20) {
            showToast(getResources().getString(R.string.login_password_condition));
        } else {
            check = true;
        }

        return check;
    }

    public String getPwd() {
        return etPwd.getText().toString();
    }

    @Override
    public void finish() {
        if (mBank != null) {
            Intent data = new Intent();
            data.putExtra("bank", mBank);
            setResult(RESULT_OK, data);
        }
        super.finish();
    }

    public static void launch(Context context) {
        launch(context, 0);
    }

    public static void launch(Context context, int requestCode) {
        Intent intent = new Intent(context, BankActivity.class);
        if (context instanceof Activity) {
            ((Activity) context).startActivityForResult(intent, requestCode);
        } else {
            context.startActivity(intent);
        }
    }

}
